//
//  CJLocationManager.m
//  DatangLife
//
//  Created by 陈建 on 2018/7/3.
//  Copyright © 2018年 DatangLife. All rights reserved.
//

#import "CJLocationManager.h"

//默认咸阳 在定位失败的时候
#define defaultLongitude @"108.70"
#define defaultLatitude @"34.33"

@interface CJLocationManager () <CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;

@end

static CJLocationManager *_singleton = nil;
@implementation CJLocationManager {
    CJLocationManagerDidUpdateLocationHandle _updateLocationHandle;
}

+ (instancetype)sharedManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _singleton = [[CJLocationManager alloc] init];
    });
    return _singleton;
}

- (void)setUpLocationManagerUpdateLocationHandle:(CJLocationManagerDidUpdateLocationHandle)updateLocationHandle {
    _updateLocationHandle = updateLocationHandle;
}

// 开始定位
- (void)startSerialLocation {
    
    if (self.canLocationFlag == NO) {
        [self defaultLocation];
        return ;
    }
    [self.locationManager startUpdatingLocation];
}
- (void)defaultLocation{
    [[NSUserDefaults standardUserDefaults] setObject:defaultLatitude forKey:kCJUserCurrentLatitude];
    [[NSUserDefaults standardUserDefaults] setObject:defaultLongitude forKey:kCJUserCurrentLongitude];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

// 停止定位
- (void)stopSerialLocation {
    [self.locationManager stopUpdatingLocation];
}

#pragma mark - ManagerDelegate



// 定位结果
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations

{
    CLLocation *currentLocation = [locations lastObject];
    // 纬度
    NSString *currentLatitude = [[NSString alloc]
                                 initWithFormat:@"%f",
                                 currentLocation.coordinate.latitude];
    
    // 经度
    NSString *currentLongitude = [[NSString alloc]
                                  initWithFormat:@"%f",
                                  currentLocation.coordinate.longitude];
    
    [[NSUserDefaults standardUserDefaults] setObject:currentLatitude forKey:kCJUserCurrentLatitude];
    [[NSUserDefaults standardUserDefaults] setObject:currentLongitude forKey:kCJUserCurrentLongitude];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    
    
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];

 NSLog(@"%f==%f",currentLocation.coordinate.longitude,currentLocation.coordinate.latitude);
    if (@available(iOS 11.0, *)) {
        [geoCoder reverseGeocodeLocation:[locations lastObject] preferredLocale:nil completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (placemarks.count > 0) {
                CLPlacemark *placeMark = placemarks.firstObject;
                
                if (_updateLocationHandle) {
                    _updateLocationHandle(placeMark, currentLatitude, currentLongitude);
                }
            }
                
            
        }];
    } else {
        // Fallback on earlier versions
        [geoCoder reverseGeocodeLocation:[locations lastObject] completionHandler:^(NSArray *placemarks, NSError *error) {
            if (placemarks.count > 0) {
                CLPlacemark *placeMark = placemarks.firstObject;
                if (_updateLocationHandle) {
                    _updateLocationHandle(placeMark, currentLatitude, currentLongitude);
                }
            }else{
                [self defaultLocation];
            }
        }];
    }
    [self stopSerialLocation];
    
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"%@",error);
    [self defaultLocation];
}


- (CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        
        _locationManager.delegate = self;
        _locationManager.distanceFilter = kCLDistanceFilterNone;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
      
        
        if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [_locationManager requestWhenInUseAuthorization];
        }
        
   
        
    }
    return _locationManager;
}

- (BOOL)canLocationFlag {
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
        //定位功能可用
        return YES;
    }else{
        //定位不能用
        [self defaultLocation];
        return NO;
    }
        
    
}

- (BOOL)hasLocation {
    return [[[NSUserDefaults standardUserDefaults] objectForKey:kCJUserCurrentLatitude] length] && [[[NSUserDefaults standardUserDefaults] objectForKey:kCJUserCurrentLongitude] length];
}
@end
